package com.ribbon.banlance;

import java.util.List;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.service.approval.localthread.ApprovalThreadLocal;
import com.service.approval.model.ApprovalInfo;

/**
 * 
 * @author Administrator
 *
 */
public class InsurancePolicyBanlance extends AbstractLoadBalancerRule {

	public InsurancePolicyBanlance() {

	}

	public Server choose(ILoadBalancer lb, Object key) {
		if (lb == null) {
			return null;
		}
		Server server = null;

		while (server == null) {
			if (Thread.interrupted()) {
				return null;
			}
			List<Server> upList = lb.getReachableServers();
			List<Server> allList = lb.getAllServers();

			int serverCount = allList.size();
			if (serverCount == 0) {
				return null;
			}
			ApprovalInfo approvalInfo = ApprovalThreadLocal.get();
			String merchantNo = approvalInfo.getMerchantNo();
			int h;
			int productHash = ((h = merchantNo.hashCode()) ^ (h >>> 16));

			int index = productHash & (serverCount - 1);
			server = upList.get(index);
			if (server == null) {
				Thread.yield();
				continue;
			}

			if (server.isAlive()) {
				return (server);
			}
			server = null;
			Thread.yield();
		}
		return server;

	}

	@Override
	public Server choose(Object key) {
		return choose(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {

	}
}
